package cn.bearspark.api.service.main.impl;

import cn.bearspark.api.vo.main.user.*;
import cn.bearspark.api.service.main.UserService;
import cn.bearspark.common.constant.GlobalConstant;
import cn.bearspark.common.dto.ResponseDTO;
import cn.bearspark.common.enumeration.RespCodeEnum;
import cn.bearspark.common.util.ConvertBeanUtil;
import cn.bearspark.currency.rpc.CurrencyRpc;
import cn.bearspark.framework.web.starter.vo.ResponseVO;
import cn.bearspark.sms.rpc.SmsRpc;
import cn.bearspark.user.rpc.UserBaseRpc;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

/**
 * @author f
 */
@Service
public class UserServiceImpl implements UserService {

    @DubboReference(check = GlobalConstant.DUBBO_CHECK)
    private UserBaseRpc userBaseRpc;
    @DubboReference(check = GlobalConstant.DUBBO_CHECK)
    private SmsRpc smsRpc;
    @DubboReference(check = GlobalConstant.DUBBO_CHECK)
    private CurrencyRpc currencyRpc;

    @Override
    public ResponseVO<Object> send(SendReqVO sendReqVO) {
        return ResponseVO.response(smsRpc.send(sendReqVO.getPhone()));
    }

    @Override
    public ResponseVO<Object> verify(VerifyReqVO verifyReqVO) {
        return ResponseVO.response(smsRpc.verify(verifyReqVO.getPhone(), verifyReqVO.getCode()));
    }

    @Override
    public ResponseVO<Object> initPassword(PasswordReqVO passwordReqVO) {
        // 验证验证码是否正确
        ResponseDTO<Object> verifyResp = smsRpc.verify(passwordReqVO.getPhone(), passwordReqVO.getCode());
        if (verifyResp.getCode() != RespCodeEnum.OK.getCode()) {
            return ResponseVO.fail(verifyResp.getMsg());
        }

        // 初始化用户的用户信息
        ResponseDTO<Object> initResp = userBaseRpc.initPassword(passwordReqVO.getPhone(), passwordReqVO.getPassword());
        if (initResp.getCode() != RespCodeEnum.OK.getCode()) {
            return ResponseVO.response(initResp);
        }

        // 初始化用户的货币信息
        currencyRpc.initCurrency((long) initResp.getData());

        return ResponseVO.success();
    }

    @Override
    public ResponseVO<Object> modifyPassword(PasswordReqVO passwordReqVO) {
        // 验证验证码是否正确
        ResponseDTO<Object> verifyResp = smsRpc.verify(passwordReqVO.getPhone(), passwordReqVO.getCode());
        if (verifyResp.getCode() != RespCodeEnum.OK.getCode()) {
            return ResponseVO.fail(verifyResp.getMsg());
        }

        return ResponseVO.response(userBaseRpc.modifyPassword(passwordReqVO.getPhone(), passwordReqVO.getPassword()));
    }

    @Override
    public ResponseVO<LoginRespVO> login(LoginReqVO loginReqVO) {
        return ResponseVO.success(ConvertBeanUtil.convert(userBaseRpc.login(
                loginReqVO.getPhone(), loginReqVO.getPassword()
        ).getData(), LoginRespVO.class));
    }
}
